package com.lims.admin.action;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import javacommon.base.BaseStruts2Action;

import cn.org.rapid_framework.page.Page;

import com.lims.admin.model.*;
import com.lims.admin.service.MenuManager;
import com.lims.admin.service.RoleManager;
import com.lims.admin.vo.query.RoleQuery;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
/**
 * @author zzh
 */
@SuppressWarnings({"serial","unchecked"})
public class RoleMenuAction extends BaseStruts2Action implements Preparable,ModelDriven{

	protected static final String LIST_JSP= "/pages/admin/RoleMenu/list.jsp";
	protected static final String MENULIST_JSP = "/pages/admin/RoleMenu/menuList.jsp";
	//redirect paths,startWith: !
	protected static final String LIST_ACTION = "!/pages/admin/RoleMenu/list.do";
	
	public void prepare() throws Exception {}

	public Object getModel() {return null;}

	private RoleManager roleManager;
	private MenuManager menuManager;
	private String rids;
	private String mids;

	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}
	
	public void setMenuManager(MenuManager menuManager) {
		this.menuManager = menuManager;
	}
	
	public String getMids() {
		return mids;
	}

	public void setMids(String mids) {
		this.mids = mids;
	}

	public void setRids(String rids) {
		this.rids = rids;
	}


	public String getRids() {
		return rids;
	}

	/** 执行搜索 */
	public String list() {
		RoleQuery query = newQuery(RoleQuery.class,null);
		Page page = roleManager.findPage(query);
		savePage(page,query);
		return LIST_JSP;
	}
	
	/**
	 * 取得菜单及当前角色下的所有菜单
	 * 多个角色时，不进行读取。
	 * @return
	 */
	public String menuList(){
		if(isNullOrEmptyString(rids)) return MENULIST_JSP;
		HttpServletRequest request = this.getRequest();
		if(rids.indexOf(",")==-1) {
			List<Menu> menus = menuManager.findMenusByRoleId(rids);
			request.setAttribute("selectedMenus", menus);
		}
		List menuAll = menuManager.findAllByLevel(2);
		List allMenu = menuManager.findAll();
		request.setAttribute("menuList", menuAll);
		request.setAttribute("allmenu", allMenu);
		return MENULIST_JSP;
	}
	
	/**
	 * 保存角色给用户
	 * @return
	 */
	public String saveMenusToRoles(){
		List<Role> roles = this.roleManager.findRolesByIds(rids);
		List<Menu> menus = this.menuManager.findMenusByIds(mids);
		for (Iterator iterator = roles.iterator(); iterator.hasNext();) {
			Role role = (Role) iterator.next();
			role.setMenus(menus);
			this.roleManager.saveOrUpdate(role);
		}
		HttpServletRequest request = this.getRequest();
		request.setAttribute("selectedMenus", menus);
		List<Menu> menuAll = menuManager.findAllByLevel(2);
		request.setAttribute("menuList", menuAll);
		request.setAttribute("saveMsg", true);
		return MENULIST_JSP;
	}

}
